package com.project.jdbc.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.project.jdbc.utils.BaseLogger;

public class BaseMVCAction extends BaseLogger {
		
		/**
		 * 得到request
		 * */
		protected HttpServletRequest getRequest() {
			return ((ServletRequestAttributes)getRequestAttributes()).getRequest();
		}
		/**
		 * 得到response
		 * */
		protected HttpServletResponse getResponse() {
			return ((ServletWebRequest)getRequestAttributes()).getResponse();
		}
		/**
		 * 得到Session
		 * */
		protected HttpSession getSession() {
			return getRequest().getSession();
		}
		/**
		 * 得到request,response,session的辅助类
		 * */
		private RequestAttributes getRequestAttributes() {
			return RequestContextHolder.getRequestAttributes();
		}
		/**
		 * 取得Request Parameter的简化方法.
		 */
		public String getParameter(String name) {
			String result = getRequest().getParameter(name);
			if (StringUtils.isBlank(result)) {
				return null;
			}
			return result.trim();
		}

		/**
		 * 取得Request Parameter的简化方法.
		 */
		public Integer getIntegerParameter(String name) {
			String result = getParameter(name);
			if (result == null) {
				return null;
			}
			return Integer.valueOf(result);
		}

		/**
		 * 取得Request Parameter的简化方法.
		 */
		public Long getLongParameter(String name) {
			String result = getParameter(name);
			if (result == null) {
				return null;
			}
			return Long.valueOf(result);
		}

		/**
		 * 取得Request Parameter的简化方法.
		 */
		public Double getDoubleParameter(String name) {
			String result = getParameter(name);
			if (result == null) {
				return null;
			}
			return Double.valueOf(result);
		}

		/**
		 * 取得Request Parameter的简化方法.
		 */
		public Date getDateParameter(String name, String dateFormat) {
			try {
				String result = getParameter(name);
				if (result == null) {
					return null;
				}
				return new SimpleDateFormat(dateFormat).parse(result);
			} catch (ParseException e) {
			}
			return null;
		}

		public Date getDateParameter(String name) {
			return getDateParameter(name, "yyyy-MM-dd");
		}

}
